<?php

namespace App\Console\Commands;

use App\Jobs\OrderHandle;
use App\Models\ProductsExchange;
use App\Models\UserExchange;
use App\Models\WalletCode;
use App\Services\MatchEngineService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class RobotSubscribe extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'robot:subscribe';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '一个简单的币币机器人下单';

    protected $currency;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        $product = ProductsExchange::select('id', 'code')->get()->toArray();
        $result = [];
        foreach ($product as $item => $value) {
            $codes = ProductsExchange::coinCut($value['code']);
            $result[$value['code']] = [
                'id' => $value['id'],
                'l_code' => $codes[0],
                'r_code' => $codes[1],
                'l_wid' => WalletCode::getWidByCode($codes[0]),
                'r_wid' => WalletCode::getWidByCode($codes[1]),
            ];
        }
        $this->currency = $result;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $channel = config('system.channel.depth');
        try {
            $redis = Redis::connection('subscribe');
            $redis->subscribe([$channel], function ($message) {
                $depth = json_decode($message, true);
                $asks = $depth['asks'][0];
                $bids = $depth['bids'][0];
                $this->crOrder('bid', $bids['price'], $bids['totalSize'], $depth);
                $this->crOrder('ask', $asks['price'], $asks['totalSize'], $depth);
                echo $depth['code'] . ' bids==>' . $bids['price'], PHP_EOL;
                echo $depth['code'] . ' ask==>' . $asks['price'], PHP_EOL;
                sleep(5);
            });
        } catch (\Exception $exception) {
            $log = sprintf('[%s] robot Subscribe Faild ==> %s ,line=>%s',
                date('Y-m-d H:i:s'), $exception->getMessage(), $exception->getLine()
            );
            echo $log, PHP_EOL;
        }
    }


    protected function crOrder($side, $price, $quantity, $depth)
    {
        $uid = 0;
        if (!isset($this->currency[$depth['code']])) {
            return;
        }

        $currency = $this->currency[$depth['code']];

        $orderInfo = UserExchange::create([
//                'order_num' => $model->createSN(),
            'uid' => $uid,
            'currency_id' => $currency['id'],
            'symbol' => $depth['name'],
            'wtprice' => $price,
            'wtprice1' => $price,
            'wtnum' => $quantity,
            'totalprice' => $price * $quantity,
            'fee' => 0,
            'type' => $side == 'bid' ? 1 : 2,
            'otype' => 1,
            'l_code' => $currency['l_code'],
            'r_code' => $currency['r_code'],
            'l_wid' => $currency['l_wid'],
            'r_wid' => $currency['r_wid'],
        ]);

        $params = json_encode([
            'type' => 'order',
            'data' => [
                'type' => 'limit', //限价单limit,市价单market
                'side' => $side, //买单bid,卖单ask
                'quantity' => $quantity, //订单数量
                'price' => $price, //价格  如果是市价这里是总金额
                'market' => $depth['code'], //交易市场
                'user_id' => $uid,
                'order_id' => $orderInfo->id,
            ]
        ]);
        echo $orderInfo->id . '完成', PHP_EOL;
        $result = MatchEngineService::run($params);
        OrderHandle::dispatch($result)->onQueue('OrderHandle');

    }

}
